package com.example.xml

import groovy.xml.MarkupBuilder

/**
 * 创建，写xml的 demo
 * @author 张威
 *
 */
class XmlCreate {
	
	static void main(String[] args) {
		
		/**
		 * MarkupBuilder用于构造整个XML文档。通过首先创建XML文档类的对象来创建XML文档。
		 * 一旦创建了对象，可以调用伪方法来创建XML文档的各种元素
		 * 
		 * <collection shelf = 'New Arrivals'> 
			   <movie title = 'Enemy Behind' /> 
			      <type>War, Thriller</type> 
			      <format>DVD</format> 
			      <year>2003</year> 
			      <rating>PG</rating> 
			      <stars>10</stars> 
			      <description>Talk about a US-Japan war</description> 
			   </movie> 
			</collection>
		 */
		def mb = new MarkupBuilder(new PrintWriter('d://groovyTest/movie.xml')); //注意这里可以保存到文件
		
		//Compose the builder
		/**
		 * mb.movies（） -这是一个标记生成器，用于创建<collection> </ collection>的头XML标签
		 * 
		 */
		def xml = mb.movies(shelf : 'New Arrivals') { 
			movie(title : 'Enemy Behind'){
				type('war,Thriller')
				format('DVD')
				year('2003')
				rating('PG')
				starts(10)
				description('Talk about a US-Japan war')
			}
		}
		
		
		def st = new MarkupBuilder(new PrintWriter('d://groovyTest/students.xml'));
		
		st.studentList(createDate:new Date()){
			student{
				id('10001')
				name('张三')
				age(20)
				city('ShangHai')
			}
		}
		
		//测试从list中循环创建xml
		def students = [ ['1263781','assad','20','Guangzhou'],
			['3729321','Kim','21','Shenzhen'],
			['3729329','Vency','22','Shanghai'] ];
		
		def st2 = new MarkupBuilder(new PrintWriter('d://groovyTest/students2.xml'))
		
		st2.studentList(createTime:new Date()){
			
			students.each { 
				e -> st2.student{
					id(e[0])
					name(e[1])
					age(e[2])
					city(e[3])
				}
			}
			
		}
		
		
	}
	
}
